package org.example.springcloud.service.impl;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.example.springcloud.entity.Order;
import org.example.springcloud.mapper.OrderMapper;
import org.example.springcloud.service.AccountService;
import org.example.springcloud.service.OrderService;
import org.example.springcloud.service.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Description:
 * @Author: y
 * @CreateDate: 8/2/21 9:32 AM
 * @Version: 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;

    public static final String SERVICE_URL = "http://seata-account-service";

    @Resource
    private RestTemplate restTemplate;


    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     */
//    @GlobalTransactional(name = "test-create-order", rollbackFor = Exception.class)
    @Override
    @GlobalTransactional
    public void create(Order order) {
        log.info("----->开始新建订单");
        //新建订单
        orderMapper.insert(order);
        //扣减库存
        log.info("----->订单微服务开始调用库存，做扣减Count");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("----->订单微服务开始调用库存，做扣减end");
        //扣减账户
        log.info("----->订单微服务开始调用账户，做扣减Money");
//        ResultVO result = restTemplate.getForObject(SERVICE_URL + "/account/decrease" + "?userId=" + order.getUserId() + "&money=" + order.getMoney(), ResultVO.class);
//        System.out.println(result);
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("----->订单微服务开始调用账户，做扣减end");
        //修改订单状态，从零到1代表已经完成
        log.info("----->修改订单状态开始");
        order.setStatus(1);
        orderMapper.updateById(order);
        log.info("----->修改订单状态结束");
        log.info("----->下订单结束了");

    }
}